package de.fhb.itunes.manager.mail;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import de.fhb.itunes.manager.Config;

public class MailSender {

	private String host;
	private String user;
	private String pwd;
	private Properties prop;
	private Properties propmail;
	private Session session;
	private String subject;
	private Address[] adresses;

	public MailSender() throws MessagingException {
		Config config = new Config();
		prop = config.getProperties();
		this.host = prop.getProperty("mail_host");
		this.user = prop.getProperty("mail_user");
		this.pwd = prop.getProperty("mail_password");

		this.subject = "test";
		// this.text = "text/plain BODY";
		propmail = new Properties();
		propmail.put("mail.smtp.auth", "true");
		propmail.put("mail.smtp.starttls.enable", "true");
		readAdresslist();
	}

	private void readAdresslist() throws AddressException {
		try {

			BufferedReader in = new BufferedReader(new FileReader(
					prop.getProperty("abs_path")+prop.getProperty("mail_list")));
			String adressen = "";
			String zeile = null;
			while ((zeile = in.readLine()) != null) {
				System.out.println(zeile);
				adressen += zeile;
			}
			adresses = InternetAddress.parse(adressen);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void send(String content, String subject) throws MessagingException {
		this.subject = subject;
		send(content);
	}

	public void send(String content) throws MessagingException {
		session = Session.getInstance(propmail);
		Transport transport = session.getTransport("smtp");
		transport.connect(host, user, pwd);
		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(user));
		boolean mindEinEmpfaenger = false;
		if(adresses != null)
		for (Address empfaenger : adresses) {
			message.addRecipient(Message.RecipientType.TO, empfaenger);
			mindEinEmpfaenger = true;
		}
		// message.setRecipients(Message.RecipientType.TO, this.adresses);
		if (mindEinEmpfaenger) {
			message.setSubject(this.subject);
			message.setContent(content, "text/html");
			transport.sendMessage(message, adresses);
			System.out.println("SEND");
			transport.close();
		} else {
			System.out.println("Fehler kein Empfänger hinzugefügt");
		}
	}
}
